import json
import random
from datetime import datetime

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from app01.utils.bootstrapForm import BootstrapModelForm
from app01.utils.pagination import Pagination


class OrderModelForm(BootstrapModelForm):
    class Meta:
        model = models.Order
        exclude = ['oid', 'admin']


def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')
    page_object = Pagination(request, queryset)
    html_text = page_object.html
    page_query_set = page_object.page_query_set

    form = OrderModelForm()
    context = {'form': form,
               'queryset': queryset,
               'page_html': html_text,
               }
    return render(request, "order_list.html", context)


@csrf_exempt
def order_add(request):
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        form.instance.oid = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S') + str(random.randint(1000, 9999))
        form.instance.admin_id = request.session['info']['id']
        form.save()
        data_dict = {'status': True}
        return HttpResponse(json.dumps(data_dict))
    data_dict = {
        'status': False,
        'errors': form.errors,
    }
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))


@csrf_exempt
def order_edit(request):
    """编辑订单"""
    uid = request.GET.get('uid')
    # print(uid)
    row_object = models.Order.objects.filter(id=uid).first()
    # print(row_object)
    if not row_object:
        data_dict = {'status': False, 'tips': '数据不存在！'}
        return JsonResponse(data_dict)
    form = OrderModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        data_dict = {'status': True}
        return JsonResponse(data_dict)
    data_dict = {
        'status': False,
        'errors': form.errors,
    }
    return JsonResponse(data_dict)


def order_delete(request):
    """删除订单"""
    uid = request.GET.get('uid')
    exists = models.Order.objects.filter(id=uid).exists()
    if not exists:
        data_dict = {'status': False, 'errors': '数据不存在！'}
        return JsonResponse(data_dict)
    models.Order.objects.filter(id=uid).delete()
    data_dict = {'status': True}
    return JsonResponse(data_dict)


def order_detail(request):
    """编辑订单判断"""
    uid = request.GET.get('uid')
    row_dict = models.Order.objects.filter(id=uid).values('title', 'price', 'status').first()
    if not row_dict:
        data_dict = {'status': False, 'errors': '数据不存在！'}
        return JsonResponse(data_dict)
    data_dict = {'status': True, 'data': row_dict}
    # print(row_dict)
    return JsonResponse(data_dict)
